package cn.kgc.mcartoon.controller;


import cn.kgc.mcartoon.dto.ResultDto;
import cn.kgc.mcartoon.dto.TokenDto;
import cn.kgc.mcartoon.entity.MmUsersDO;
import cn.kgc.mcartoon.service.MmUsersService;
import cn.kgc.mcartoon.utils.MD5Utils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author christopher
 * @since 2021-09-23
 */
@RestController
@RequestMapping("api/user")
@Api(tags = "用户模块",value = "用户接口MmUsersController")
public class MmUsersController {

    @Autowired
    private MmUsersService usersService;

    private Logger log = LoggerFactory.getLogger(this.getClass());


    @ApiResponses({
            @ApiResponse(responseCode = "2000", description = "保存成功"),
            @ApiResponse(responseCode = "4000", description = "保存失败")
    })
    @ApiOperation("用户登录——login")
    @PostMapping("login")
    public ResultDto login3(@RequestBody MmUsersDO user){

        return usersService.login(user);
    }

    @ApiOperation("解析token")
    @GetMapping("getClaims")
    public ResultDto getClaims(HttpServletRequest request){
        //获取请求头中键为Authorization的值
        final String authHeader = request.getHeader("Authorization");
        //截取获得的字符串中的和token相关的内容
        final String token = authHeader.substring(8,authHeader.lastIndexOf("")-1);
//        System.out.println(token.getToken());
////
        //解析token获得subject和id
        Claims claims = Jwts.parser()
                .setSigningKey("m-cartoon")
                .parseClaimsJws(token).getBody();
////
//        log.info("suject:{}",claims.getSubject());

        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("id",claims.getId());
        tokenMap.put("subject",claims.getSubject());
        return ResultDto.ok(tokenMap);
    }
}

